program least_squares
  implicit none
  character(len=20) :: filename
  integer :: ierror, n = 0
  real :: slope, x, y, x_bar, y_bar, y_int, sum_x=0.0, sum_y=0.0, sum_x2=0.0, sum_xy=0

  write(*,*) 'input dat file name :'
  read(*,*) filename
  open(unit=3, file=filename, status='old', action='read', iostat=ierror)

  openif: if(ierror /= 0) then
     write(*,*) 'open file error'
  else
     read_dat: do
        read(3,*,iostat=ierror) x, y
        if(ierror /= 0) exit
        n = n+1
        sum_x = sum_x + x
        sum_y = sum_y + y
        sum_x2 = sum_x2 + x**2
        sum_xy = sum_xy + x*y
     end do read_dat

     if(ierror > 0) then
        write(*,*) 'read data occured error'
     else
        write(*,*) 'reach to file end, have ', n, ' value'
     end if

     x_bar = sum_x/real(n)
     y_bar = sum_y/real(n)
     slope = (sum_xy - sum_x) / (sum_x2 - sum_x*x_bar)
     y_int = y_bar - slope * x_bar

     write(*,100) slope, y_int, n
100  format(' ', 'slope   = ', F12.4/, 1x, 'intercept  = ', F12.4/, 1x, 'number of points  = ', I12)
     close(unit=3)
  end if openif
end program least_squares
